<template>
  <div id="app">
    <el-container class="layout-container">
      <el-header class="app-header">
        <div class="header-content">
          <h1 class="app-title">
            <el-icon class="title-icon" @click="goHome"><Reading /></el-icon>
            阅读笔记复习系统
          </h1>
          <div class="header-actions">
            <el-badge
                :value="todayReviewCount"
                :max="99"
                v-if="todayReviewCount > 0"
                class="reminder-badge"
            >
              <el-button
                  type="primary"
                  @click="showReminderModal"
                  :icon="Bell"
                  class="reminder-btn"
              >
                今日复习
              </el-button>
            </el-badge>
          </div>
        </div>
      </el-header>

      <el-main class="app-main">
        <router-view
            :key="routerKey"
            @review-count-update="handleReviewCountUpdate"
        />
      </el-main>
    </el-container>

    <!-- 复习提醒弹窗 -->
    <ReminderModal
        :visible="reminderVisible"
        :reviews="todayReviews"
        @close="reminderVisible = false"
        @complete="handleCompleteReview"
    />
  </div>
</template>

<script>
import { ref, onMounted, provide } from 'vue'
import { useRouter } from 'vue-router'
import { ElNotification, ElMessage } from 'element-plus'
import ReminderModal from '@/components/ReminderModal.vue'
import {checkTodayReviews, manualTrigger} from '@/api/notes'

export default {
  name: 'App',
  components: {
    ReminderModal
  },
  setup() {
    const router = useRouter()
    const reminderVisible = ref(false)
    const todayReviews = ref([])
    const todayReviewCount = ref(0)
    const routerKey = ref(0) // 用于强制刷新路由组件
    //通知引用保存
    const reviewNotification = ref(null)
    // 全局刷新函数
    const refreshAllData = async () => {
      console.log('开始全局数据刷新...')

      // 强制重新加载路由组件
      routerKey.value += 1

      // 重新加载今日复习任务
      await loadTodayReviews()

      console.log('全局数据刷新完成')
    }

    // 检查今日复习任务
    const loadTodayReviews = async () => {
      try {
        console.log('加载今日复习任务...')
        const response = await checkTodayReviews()
        if (response.success) {
          todayReviews.value = response.data.reviews || []
          todayReviewCount.value = response.data.count || 0

          console.log('今日复习任务加载完成:', {
            count: todayReviewCount.value,
            reviews: todayReviews.value
          })

          // 如果有复习任务，显示通知
          if (response.data.count > 0) {
            showNotification(response.data.count)
          }
        }
      } catch (error) {
        console.error('加载今日复习任务失败:', error)
      }
    }

    // 显示通知
    const showNotification = (count) => {
      // 如果已有通知，先关闭
      if (reviewNotification.value) {
        reviewNotification.value.close()
      }

      reviewNotification.value = ElNotification({
        title: '复习提醒',
        message: `今天有 ${count} 条笔记需要复习`,
        type: 'info',
        duration: 0,
        offset: 100,
        customClass: 'review-notification',
        onClick: () => {
          showReminderModal()
        }
      })
    }
    //关闭 通知
    const closeAllNotifications = () => {
      if (reviewNotification.value) {
        reviewNotification.value.close()
        reviewNotification.value = null
      }
    }

    // 显示提醒弹窗
    const showReminderModal = () => {
      reminderVisible.value = true
    }

    // 处理复习完成
    const handleCompleteReview = async (noteId, stage) => {
      console.log('处理复习完成:', { noteId, stage })

      try {
        // 从列表中移除已完成的复习项
        todayReviews.value = todayReviews.value.filter(
            item => !(item.id === noteId && item.stage === stage)
        )
        todayReviewCount.value = todayReviews.value.length

        // 显示成功消息
        ElMessage.success('复习任务已完成！')

        // 刷新所有数据
        await refreshAllData()

        // 如果所有复习都完成了，显示特别提示并关闭弹窗
        if (todayReviews.value.length === 0) {
          // 关闭之前显示的通知
          closeAllNotifications()

          setTimeout(() => {
            ElMessage.success('恭喜！今日所有复习任务已完成！')
            reminderVisible.value = false
          }, 500)
        }

      } catch (error) {
        console.error('处理复习完成失败:', error)
        ElMessage.error('处理复习完成时出现错误')
      }
    }

    // 处理子组件传来的复习数量更新
    const handleReviewCountUpdate = (count) => {
      todayReviewCount.value = count
    }

    // 回到主页
    const goHome = () => {
      router.push("/")
    }

    async function dailyScheduler() {
      // eslint-disable-next-line no-constant-condition
      while (true) {
        const now = new Date();
        const target = new Date();
        target.setHours(8, 20, 0, 0);

        if (now > target) {
          target.setDate(target.getDate() + 1);
        }

        const waitTime = target.getTime() - now.getTime();

        console.log(`等待 ${Math.round(waitTime / 1000 / 60)} 分钟直到 8:20`);

        await new Promise(resolve => setTimeout(resolve, waitTime));

        // 执行任务
        loadManualTrigger();
      }
    }
    // 启动
    dailyScheduler().catch(console.error);

    // 主动调用
    const loadManualTrigger = async () => {
      try {
        console.log('主动调用定时任务...')
        const response = await manualTrigger()
        if (response.success) {
          console.log('主动调用定时任务成功')
        }
      } catch (error) {
        console.error('主动调用定时任务失败:', error)
      }
    }

    // 提供刷新函数给子组件
    provide('refreshAllData', refreshAllData)

    onMounted(() => {
      loadTodayReviews()
      // 定时检查复习任务（每5分钟检查一次）
      setInterval(() => {
        loadTodayReviews()
      }, 300000)

      const originalError = console.error
      console.error = (...args) => {
        if (args[0] && typeof args[0] === 'string' &&
            (args[0].includes('ResizeObserver') ||
                args[0].includes('ResizeObserver loop completed with undelivered notifications'))) {
          return
        }
        originalError.apply(console, args)
      }
      window.addEventListener('error', (e) => {
        if (e.message && e.message.includes('ResizeObserver')) {
          e.preventDefault()
          e.stopPropagation()
          return false
        }
      })
    })

    return {
      routerKey,
      reminderVisible,
      todayReviews,
      todayReviewCount,
      showReminderModal,
      handleCompleteReview,
      handleReviewCountUpdate,
      goHome,
      refreshAllData // 暴露给模板，便于调试
    }
  }
}
</script>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;
}

.app-header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  padding: 0 24px;
  border-bottom: 1px solid #e6e6e6;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.app-title {
  margin: 0;
  color: #409eff;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  cursor: pointer;
}

.title-icon {
  font-size: 24px;
}

.app-main {
  background: #f5f7fa;
  padding: 20px;
  overflow: auto;
}

.reminder-badge {
  margin-right: 10px;
}

.reminder-btn {
  font-weight: 500;
}

// 响应式设计
@media (max-width: 768px) {
  .app-header {
    padding: 0 16px;
  }

  .app-title {
    font-size: 18px;
  }

  .header-content {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .app-main {
    padding: 16px;
  }
}
</style>